//
//  SHComposeTextView.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/27.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit

class SHComposeTextView: UITextView {
    
    override var font: UIFont?{
        
        didSet{
            
            placeholderLabel.font = font
        }
    }
    
    var placeholder: String?{
        
        didSet{
            
            placeholderLabel.text = placeholder
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        
        addSubview(placeholderLabel)
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "valueChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    func valueChange(){
        
        placeholderLabel.hidden = self.hasText()
    }
    
    private lazy var placeholderLabel: UILabel = {
        let lab = UILabel()
        
        lab.numberOfLines = 0
        
        lab.textColor = UIColor.grayColor()
        
        return lab
        
    }()
    
}
